#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name:       get_alerts
   Description:     get_alerts
   Author:          Pin
   date:            2023/2/24 18:29:38
   Version:         1.0 (20230225)
   Change Log:      1.0:
                        err output
                        std output
                        args
"""
import sys

import requests

#_host = '222.168.154.194:8081'
_host = '192.168.199.130:8080'
_req_url = f'http://{_host}/cgftBackend/openApi/obsMsg/getAlerts'
#timeout in seconds
_timeout = 15   


def get_alerts(trigger_name: str) -> list or None:
    """
        输入： trigger_name
        输出：
            若正常完成查询，则返回 警报信息列表 。若查询过程中，程序执行出错。则返回 None 。
            结果示例：
                [
                    {
                        "recId": 185,
                        "triggerName": "1155864",
                        "alertRa": 272.1598,                            (deg)
                        "alertDec": -20.4006,                           (deg)
                        "alertError": 0.0,                              (arcsec)
                        "alertTime": "2023-02-23 23:55:01.000"          (UT)
                    }
                ]

        Note:
            结果列表中的数据，已依照时间先后排列。
            目前仅支持7天内的数据查询，原因在于：数据库设置了每7天的自动归档。
    """
    params = {'triggerName': trigger_name}

    try:
        r = requests.get(_req_url, params=params, timeout=_timeout)
        if r.status_code == requests.codes.ok:
            try:
                rj = r.json()
                if rj.get('errcode') == 0:
                    return rj.get('data')
                else:
                    print(rj.get('msg'), file=sys.stderr)
            except Exception as e:
                print(e, file=sys.stderr)
        else:
            r.raise_for_status()
    except Exception as e:
        print(e, file=sys.stderr)


def get_all_info(trigger_name: str):
    res = get_alerts(trigger_name)
    if not res:
        res = [{}]
    for i in res:
        print(f"{i.get('triggerName')}\t{i.get('alertRa')}\t{i.get('alertDec')}\t{i.get('alertError')}")


def get_min_info(trigger_name: str):
    res = get_alerts(trigger_name)
    if not res:
        res = [{}]
    else:
        res_will_remove = []
        min_err = None
        for i in res:
            if min_err is None:
                min_err = i.get('alertError')
            else:
                if i.get('alertError') >= min_err:
                    res_will_remove.append(i)
        for i in res_will_remove:
            res.remove(i)
    for i in res:
        print(f"{i.get('triggerName')}\t{i.get('alertRa')}\t{i.get('alertDec')}\t{i.get('alertError')}")


if __name__ == '__main__':
    # tn = '1155864'
    # _timeout = 0.01
    # res = get_alerts(tn)
    # print(res)
    # get_all_info(tn)
    # get_min_info(tn)

    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('triggerName', type=str, help='the trigger_name you want to search')
    parser.add_argument('-a', '--all', dest='isAll', action='store_true',
                        help='return all res or min. if not set, return the min.')
    args = parser.parse_args()
    triggerName = args.triggerName
    isAll = args.isAll
    # print(triggerName, isAll)
    if isAll:
        get_all_info(triggerName)
    else:
        get_min_info(triggerName)
    pass
